package com.kc.gb.device.configurations;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.kc.gb.device.common.contants.CacheConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CaffeineCacheConfiguration {

    @Bean(CacheConst.Caffeine.MANAGER_3MIN)
    @ConditionalOnMissingBean(CaffeineCacheManager.class)
    public CaffeineCacheManager caffeineCacheManager() {
        CaffeineCacheManager defaultCacheManager = new CaffeineCacheManager(CacheConst.Caffeine.MANAGER_3MIN);
        defaultCacheManager.setAllowNullValues(true);
        Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder()
                .recordStats()
                .initialCapacity(100)
                .maximumSize(1000)
                .expireAfterWrite(3, TimeUnit.MINUTES);
        defaultCacheManager.setCaffeine(caffeineBuilder);
        log.info("the caffeine cache manager is loaded successfully!");
        return defaultCacheManager;
    }
}
